package cc.mxtt.mvc.interceptor;

import java.util.Date;

import cc.mxtt.common.core.GlobalKey;
import cc.mxtt.mvc.model.Log;
import cc.mxtt.mvc.model.Menu;
import cc.mxtt.mvc.model.User;
import cc.mxtt.mvc.service.LogService;
import cc.mxtt.mvc.service.impl.LogServiceImpl;
import cc.mxtt.mvc.service.impl.MenuServiceImpl;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.JsonKit;


public class MenuLogInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		User user = inv.getController().getSessionAttr(GlobalKey.CurrentUser);
		if (user==null) {
			inv.getController().redirect("/");
		}else{
			LogService logService = new LogServiceImpl();
			Log log = new Log();
			log.set("username", user.getStr("username"));
			log.set("nickname", user.getStr("nickname"));
			if("0:0:0:0:0:0:0:1".equals(inv.getController().getRequest().getRemoteAddr().toString())){
				log.set("ip_address", "127.0.0.1");
			}else{
				log.set("ip_address", inv.getController().getRequest().getRemoteAddr());
			}
			log.set("request_name", logService.getMethodName(inv.getActionKey()));
			log.set("request_url", inv.getActionKey());
			log.set("url_para", inv.getController().getPara());
			if(!"/menu/add".equals(inv.getActionKey())){
				String id = inv.getController().getPara("id");
				Menu old_menu = new MenuServiceImpl().findById(id);
				log.set("old_values", JsonKit.toJson(old_menu));
			}
			log.set("new_values", JsonKit.toJson(inv.getController().getParaMap()));
			log.set("operation_time", new Date());
			inv.invoke(); //拦截器放行
			logService.create(log);  //控制器操作成功后再写入日志
		}
	}


}
